package com.setup.trac.controller.validator;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.setup.trac.pojo.Allegati;
import com.setup.trac.pojo.condition.FindAllegatiByMD5AndTemporaneo;
import com.setup.trac.service.SearchService;
import com.setup.trac.util.SQLCondition;
import com.setup.trac.util.TracSetupUtil;
import com.setup.trac.web.form.TicketForm;

public class AllegatoValidator implements Validator {

	private int maxFileSize;
	private TracSetupUtil tracSetupUtil;
	private SearchService searchService;

	public boolean supports(Class<?> clazz) {
		return clazz.isAssignableFrom(TicketForm.class);
	}

	public void validate(Object command, Errors errors) {
		TicketForm tf = (TicketForm) command;
		ValidationUtils.rejectIfEmpty(errors, "file", "",
				"Selezionare il file da allegare!");
		if (!errors.hasErrors()) {
			if (tf.getFile().length > getMaxFileSize()) {
				errors.rejectValue("file", "",
						"Le dimensioni del file sono troppo grandi.");
			}
			try {
				String md5 = tracSetupUtil.getMD5Checksum(tf.getFile());
				SQLCondition sqlCondition = new FindAllegatiByMD5AndTemporaneo(
						md5);
				Allegati[] allegato = getSearchService().find(new Allegati[0],
						sqlCondition, Allegati.class);
				if (allegato == null || allegato.length == 1) {
					errors.rejectValue("file", "", "Allegato gia' inserito");
				}
			} catch (NoSuchAlgorithmException e) {
			} catch (IOException e) {
			}
		}

	}

	public void setMaxFileSize(int maxFileSize) {
		this.maxFileSize = maxFileSize;
	}

	public int getMaxFileSize() {
		return maxFileSize;
	}

	public TracSetupUtil getTracSetupUtil() {
		return tracSetupUtil;
	}

	public void setTracSetupUtil(TracSetupUtil tracSetupUtil) {
		this.tracSetupUtil = tracSetupUtil;
	}

	public SearchService getSearchService() {
		return searchService;
	}

	public void setSearchService(SearchService searchService) {
		this.searchService = searchService;
	}

}
